import os
import argparse
import json
import time

args = None

def get_auth():
	if args.auth!="":
		return "-i "+ args.auth
	else:
		return ""

def stop_mongod(infos):
	print "begin stop mongod..."
	for info in infos:
		cmd = 'mongo localhost:%d/admin --eval="db.shutdownServer({force: true})"'%(info["port"])
		fp = open("tmp_cmd", 'wt')
		fp.write(cmd)
		fp.close()
		os.system('plink %s %s@%s -m tmp_cmd'%( get_auth(), info["login_user"], info["host"]))
	print "stop mongod...[OK]"

def start_mongod(name, infos):
	print "begin start mongod..."
	for info in infos:
		cmd1 = "mkdir -p %s\n"% info["dbpath"]
		cmd2 = "mkdir -p %s\n"% info["logpath"][0:info["logpath"].rfind("/")]
		cmd3 = "mongod --replSet %s --dbpath %s --logpath %s --bind_ip 0.0.0.0 --port %d --fork"%(name, info["dbpath"], info["logpath"], info["port"])
		fp = open("tmp_cmd", 'wt')
		fp.write(cmd1)
		fp.write(cmd2)
		fp.write(cmd3)
		fp.close()
		os.system('plink %s %s@%s -m tmp_cmd'%( get_auth(), info["login_user"], info["host"]))
	print "start mongod...[OK]"
	
def rs_init(name, infos):
	print "begin init rs..."
	members = ''
	for info in infos:
		members += '{"_id":%d,"host":"%s:%d"},'%(info["_id"], info["host"], info["port"])
	cmd = 'config = {"_id":"%s", "members":[%s]}; rs.initiate(config)'%(name, members)
	cmd2 = "mongo localhost:%d/admin --eval='%s'"%(info["port"], cmd)
	print cmd2
	fp = open("tmp_cmd", 'wt')
	fp.write(cmd2)
	fp.close()
	os.system('plink %s %s@%s -m tmp_cmd'%( get_auth(), info["login_user"], info["host"]))
	print "init rs...[OK]"

if __name__ == "__main__":
	parser = argparse.ArgumentParser(description='rs_tool_stop',formatter_class=argparse.RawDescriptionHelpFormatter)
	parser.add_argument("--cfg", default="cfgs.json", help="cfg filename", type=str)
	parser.add_argument("--auth", default="", help="private key file for user authentication", type=str)
	args = parser.parse_args()
	
	fp = open(args.cfg, 'rt')
	jstr = fp.read()
	fp.close()
	jobj = json.loads(jstr)
	for k,v in jobj.items():
		stop_mongod(v)
		print "sleep 5 sec..."
		time.sleep(5)
		start_mongod(k, v)
		print "sleep 5 sec..."
		time.sleep(5)
		rs_init(k, v)
	os.system('del /F /S /Q tmp_cmd')